import Axios from './axios'
import { AxiosOptions, InterceptorsOption } from '@/types/axios'
import { checkErrorStatus } from './checkErrorStatus'
import { retry } from './axiosRetry'
import useAdmin from '@/store/useAdmin'
import { ElMessage } from 'element-plus'

const _RequestInterceptors: InterceptorsOption = {
    requestResolve(config) {
        const admin = useAdmin()
        admin.getToken && (config.headers['Authorization'] = `Bearer ${admin.getToken}`)
        return config
    },
    requestReject(error) {
        return error
    },
    responseResolve(res) {
        if (res.data.error_code == 401000) {
            useAdmin().logout()
            ElMessage.error({
                message: '登录已失效，请重新登录', onClose() {
                    window.location.href = '/admin/login'
                },
            })
        }
        const admin = useAdmin()
        if (res.headers.has('New-Token')) {
            admin.setToken(res.headers['new-token'], res.headers['new-expires-in'])
        }
        return res
    },
    responseReject(instance, err) {
        let message = err.code === 'ECONNABORTED' ? '请求超时' : undefined
        // 判断本次请求是否被取消
        if (instance.isCancel(err)) {
            return Promise.reject(err)
        }
        checkErrorStatus(err.response?.status, message, (message) => { console.log(message) })

        // 实现错误重连
        return retry(instance, err)
    },
}

const cof: AxiosOptions = {
    baseURL: "/api",
    timeout: 50000,
    interceptorsOption: _RequestInterceptors,
    abortRepetitiveRequest: true,
    retryConfig: {
        count: 3,
        waitTime: 600
    },
    throttle: 500
}

export default new Axios(cof)